package cn.dujc.superkid.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.security.MessageDigest;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import cn.dujc.core.ui.BaseActivity;
import cn.dujc.core.util.ToastUtil;
import cn.dujc.superkid.R;
import cn.dujc.superkid.api.HttpHelper;
import cn.dujc.superkid.api.QMap;
import cn.dujc.superkid.api.Result;
import cn.dujc.superkid.api.ResultCallBack;
import cn.dujc.superkid.bean.CreateOrderResult;
import cn.dujc.superkid.bean.PayResult;
import cn.dujc.superkid.bean.RegisterResult;
import cn.dujc.superkid.utils.MD5Util;
import cn.dujc.superkid.utils.Preferences;
import cn.dujc.superkid.wxapi.MD5;

/**
 * Created by Administrator on 2018/10/25 0025.
 */

public class PayActivity extends BaseActivity implements View.OnClickListener {
    private String title;
    private String price;
    private String price1;
    private boolean isSelect;
    private ImageView checkView;
    private View paySubmit;
    private TextView vipName, vipPrice;
    private String product_id;
    private String orderCode;

    @Override
    public int getViewId() {
        return R.layout.activity_pay;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        setTitle("会员充值");
        initBroadCast();
        title = getIntent().getStringExtra("time");
        product_id = getIntent().getStringExtra("product_id");
        price = getIntent().getStringExtra("price");
        checkView = findViewById(R.id.pay_check_view);
        checkView.setOnClickListener(this);
        paySubmit = findViewById(R.id.pay_submit);
        paySubmit.setOnClickListener(this);
        vipName = findViewById(R.id.pay_vip_name);
        vipPrice = findViewById(R.id.pay_vip_price);
        vipName.setText(title);
//        vipPrice.setText(price);
        createOrder();
    }

    BroadcastReceiver broadcastReceiver;

    private void initBroadCast() {
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals("WxPaySuccess")) {
                    finish();
                }
            }
        };
        IntentFilter filter = new IntentFilter("WxPaySuccess");
        registerReceiver(broadcastReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);


    }
    @Override
    public void onClick(View v) {
        if (v == checkView) {
            checkView.setImageResource(isSelect ? R.drawable.pay_no_select : R.drawable.pay_is_select);
            isSelect = !isSelect;
        } else if (v == paySubmit) {
            pay(isSelect);
        }
    }

    private void pay(boolean isSelect) {
        if (isSelect) {
            if (price1 != null) {
                paySubmit.setClickable(false);
                toPay();
            }else{
                ToastUtil.showToast(this,"正在加载数据，请稍后再试");
            }
        } else {
            ToastUtil.showToast(this, "请选择支付方式");
            return;
        }
    }

    private void toPay() {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        HttpHelper.getAnswerOnline().pay(QMap.build()
                .put("type", product_id)
                .put("total", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                .put("number", orderCode)
                .create()).enqueue(new ResultCallBack<Result<PayResult>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, final Result<PayResult> body) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PayResult payResult = body.getData();
                        IWXAPI api = WXAPIFactory.createWXAPI(mActivity, "wxfa28fbde69421b59");
                        PayReq request = new PayReq();
                        request.appId = payResult.getAppid();
                        request.partnerId = payResult.getPartnerid();
                        request.prepayId = payResult.getPrepay_id();
                        request.nonceStr = payResult.getNonce_str();
                        request.packageValue = payResult.getPackageX();
                        request.timeStamp = payResult.getTimestamp() + "";
                        LinkedHashMap<String, String> signParams = new LinkedHashMap<>();
                        signParams.put("appid", request.appId);
                        signParams.put("noncestr", request.nonceStr);
                        signParams.put("package", request.packageValue);
                        signParams.put("partnerid", request.partnerId);
                        signParams.put("prepayid", request.prepayId);
                        signParams.put("timestamp", request.timeStamp);
                        request.sign = createSign(signParams);
                        api.sendReq(request);
                    }
                }).start();
            }

            @Override
            public void onFailureCallback(int code, String msg) {
                ToastUtil.showToast(mActivity, msg);
            }
        });
    }

    private void createOrder() {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        HttpHelper.getAnswerOnline().memberCreateOrder(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                .put("logincode", loginResult.getLogincode())
                .put("product_id", product_id)
                .create()).enqueue(new ResultCallBack<Result<CreateOrderResult>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<CreateOrderResult> body) {
                vipPrice.setText("¥" + body.getData().getPrice());
                orderCode = body.getData().getNumber();
                price1 = body.getData().getPrice();
            }

            @Override
            public void onFailureCallback(int code, String msg) {
                ToastUtil.showToast(mActivity, msg);
            }
        });
    }

    /**
     * 微信支付签名算法sign
     *
     * @param parameters
     * @return
     */
    public String createSign(LinkedHashMap<String, String> parameters) {

        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k)
                    && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + "LaDdftrgDgsrgBsa124D7eeeWd51212w"); //KEY是商户秘钥
        String sign = getMessageDigest(sb.toString().getBytes()).toUpperCase();

        return sign; // D3A5D13E7838E1D453F4F2EA526C4766
        // D3A5D13E7838E1D453F4F2EA526C4766
    }

    /**
     * md5加密
     *
     * @param buffer
     * @return
     */
    private String getMessageDigest(byte[] buffer) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取时间戳
     *
     * @return
     */
    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 调起微信APP支付，签名
     * 生成签名
     */
    private String genPackageSign(LinkedHashMap<String, String> params, String key) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey());
            sb.append('=');
            sb.append(entry.getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(key);

        String packageSign = getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return packageSign;
    }
}
